<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/backend' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>博文管理</el-breadcrumb-item>
      <el-breadcrumb-item>编辑用户</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input
            placeholder="输入内容查找相似的管理员信息"
            class="input-with-select"
            v-model="queryUsers.query"
            clearable
            @change="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="dialogFormVisible = true">添加账号</el-button>
          <el-dialog title="添加管理员信息" :visible.sync="dialogFormVisible">
            <el-form :model="addUser" :rules="rules" ref="addUser" label-width="100px" class="addUser-form">
              <el-form-item label="账号" prop="account">
                <el-input v-model="addUser.account" placeholder="输入账号" ></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <!-- <el-input v-model="addUser.password"></el-input>  -->
                <el-input placeholder="输入密码" v-model="addUser.password" show-password></el-input>
              </el-form-item>
              <el-form-item label="昵称" prop="nickname">
                <el-input v-model="addUser.nickname" placeholder="输入昵称" ></el-input>
              </el-form-item>
              <el-form-item label="账户类型" prop="userType">
                <el-select v-model="addUser.userType" placeholder="请选择用户类型">
                  <el-option  label="管理员" value="管理员"></el-option>
                  <el-option  label="普通用户" value="普通用户"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="性别">
                <el-radio-group v-model="addUser.sex">
                  <el-radio label="保密">保密</el-radio>
                  <el-radio label="男">男</el-radio>
                  <el-radio label="女">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="生日">
                <el-date-picker v-model="addUser.birthday" align="right" type="date" placeholder="选择日期"  :picker-options="pickerOptions"></el-date-picker>
              </el-form-item>
              <!-- <el-form-item label="头像" prop="avatar">
                <el-input v-model="addUser.avatar" placeholder="请输入头像地址" ></el-input>
              </el-form-item> -->
              <el-form-item label="简介">
                <el-input v-model="addUser.Introduction" placeholder="请输入简介" ></el-input>
              </el-form-item>
              <el-form-item label="地区">
                <el-input v-model="addUser.district" placeholder="请输入地区" ></el-input>
              </el-form-item>
              <el-form-item label="学校">
                <el-row class="demo-autocomplete">
                  <el-col :span="12">
                    <el-autocomplete
                      class="inline-input"
                      v-model="addUser.school"
                      :fetch-suggestions="querySearch"
                      placeholder="选择学校"
                      @select="handleSelect"
                    ></el-autocomplete>
                  </el-col>
                </el-row>
                <!-- <el-select v-model="addUser.school" placeholder="请选择学校">
                  <el-option v-for="slItem in schools" :key="slItem.school_id" :label="slItem.name" :value="slItem.school_id"></el-option>
                </el-select> -->
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm('addUser')">发布</el-button>
                <el-button @click="resetForm('addUser')">重置</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
          </el-col>
      </el-row>
      <el-table stripe border :data="userList" height="350" >
        <!-- <el-table-column type="selection" width="40"></el-table-column> -->
        <el-table-column type="index" label="编号"></el-table-column>
        <el-table-column prop="account" label="账号"></el-table-column>
        <el-table-column prop="password" label="密码"></el-table-column>
        <el-table-column prop="userType" label="用户类型"></el-table-column>
        <el-table-column prop="rank" label="等级"></el-table-column>
        <el-table-column prop="regtime" label="注册时间"></el-table-column>
        <el-table-column prop="nickname" label="昵称"></el-table-column>
        <el-table-column prop="avatar" label="头像" ></el-table-column>
        <el-table-column prop="Introduction" label="简介"></el-table-column>
        <el-table-column prop="sex" label="性别"></el-table-column>
        <el-table-column prop="birthday" label="生日"></el-table-column>
        <el-table-column prop="district" label="地区"></el-table-column>
        <el-table-column prop="school" label="学校"></el-table-column>
        <el-table-column prop label="操作" fixed="right" width="180">
          <template slot-scope="scope">
            <div>
              <!--修改-->
              <el-button type="primary" icon="el-icon-edit" circle @click="editOpen(scope.row)"></el-button>
              <!-- 弹出框，修改-->
              <el-dialog title="编辑用户" :visible.sync="deitFormVisible" :modal-append-to-body='false'>
                <el-form :model="edituser" :rules="rules" ref="edituser" label-width="100px" class="Posts-form">
                  <el-form-item label="账号" prop="account">
                    <el-input v-model="edituser.account"></el-input>
                  </el-form-item>
                  <el-form-item label="密码" prop="password">
                    <!-- <el-input v-model="edituser.password"></el-input> -->
                    <el-input placeholder="输入密码" v-model="edituser.password" show-password></el-input>
                  </el-form-item>
                  <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="edituser.nickname"></el-input>
                  </el-form-item>
                  <el-form-item label="账户类型" prop="userType">
                    <el-select v-model="edituser.userType" placeholder="请选择用户类型">
                      <el-option  label="管理员" value="管理员"></el-option>
                      <el-option  label="普通用户" value="普通用户"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="性别">
                    <el-radio-group v-model="edituser.sex">
                      <el-radio label="保密">保密</el-radio>
                      <el-radio label="男">男</el-radio>
                      <el-radio label="女">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="生日">
                    <!-- <el-input v-model="edituser.birthday"></el-input> -->
                    <el-date-picker v-model="edituser.birthday" align="right" type="date" placeholder="选择日期"  :picker-options="pickerOptions"></el-date-picker>
                  </el-form-item>
                  <el-form-item label="头像">
                    <el-input v-model="edituser.avatar"></el-input>
                  </el-form-item>
                  <el-form-item label="简介">
                    <el-input v-model="edituser.Introduction"></el-input>
                  </el-form-item>
                  <el-form-item label="地区">
                    <el-input v-model="edituser.district"></el-input>
                  </el-form-item>
                  <el-form-item label="学校">
                    <el-select v-model="edituser.school" placeholder="请选择类别">
                      <el-row class="demo-autocomplete">
                        <el-col :span="12">
                          <el-autocomplete
                            class="inline-input"
                            v-model="addUser.school"
                            :fetch-suggestions="querySearch"
                            placeholder="选择学校"
                            @select="handleSelect"
                          ></el-autocomplete>
                        </el-col>
                      </el-row>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="edit(edituser)">修改</el-button>
                    <el-button @click="resetForm('edituser')">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-dialog>
              <!--分配权限-->
              <el-button type="primary" icon="el-icon-s-tools" circle></el-button>
              <!--删除-->
              <el-button type="danger" icon="el-icon-delete" circle slot="reference"  @click="dialogVisible = true"></el-button>
              <el-dialog
                title="提示"
                :visible.sync="dialogVisible"
                width="30%"
                :before-close="handleClose"
                :modal-append-to-body='false'>
                <span>确定删除？</span>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="dialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="del(scope.row.user_id)">确 定</el-button>
                </span>
              </el-dialog>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryUsers.pagenum"
        :page-sizes="[3, 5, 10, 100]"
        :page-size="queryUsers.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      queryUsers: {
        query: "",
        pagenum: 1, //当前页码
        pagesize: 3 //每页显示条数
      },
      userList: [],
      addUser: {
        account:"",//账号
        password:"",//密码
        userType:"",//账户类型
        regtime:"",//注册时间
        nickname:"",//昵称
        avatar:"",//头像
        Introduction:"",//简介
        sex:"保密",//性别
        birthday:"",//生日
        district:"",//地区
        school:"",//学校
      },
      edituser:{
        user_id:"",
        account:"",
        password:"",
        userType:"",
        regtime:"",
        nickname:"",
        avatar:"",
        Introduction:"",
        sex:"",
        birthday:"",
        district:"",
        school:"",
      },
      rules: {
        account: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        nickname: [
           { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 0, max: 5, message: '长度在 0 到 5 个字符', trigger: 'blur' }
        ],
        userType: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ],
      },
      schools:[],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }],
        imageUrl: ''
      },

      sorts:[],
      contnetSorts:[],
      total: 0,
      dialogTableVisible: false,
      dialogFormVisible: false,//添加文章
      formLabelWidth: "120px",
      visible: false,
      dialogVisible: false,//删除文章
      deitFormVisible:false,//修改文章
      editForm:{
        id:"",
        rid:"",
        username: "",
        password: "",
        email: "",
        mobile: ""
      }
    };
  },
  created() {
    this.getSchools();
    this.getUserList();
  },
  methods: {
    // 获取指定数据
    async getUserList() {
      let queryUsers = this.queryUsers;
      const {data:res} = await this.$http.post("selUser",{queryUsers});
      // console.log(res);
     if (res.status !== 200) {
        this.$message.error("获取用户列表失败");
      } else {
        this.userList = res.message;
        if(queryUsers.query ==""){
          const {data:totalRes} = await this.$http.get("getAllUser");
          // console.log(totalRes.message.length);
          if(totalRes.status != 200){
          this.$message.error("获取用户列表失败");
          }else{
            this.total = totalRes.message.length;
          }
        }else{
          this.total = res.message.length;
        }
        // console.log(this.userList);
      }
      this.queryUsers.query=""
    },
    // 首先获取学校详情
    async getSchools(){
      const {data:res} = await this.$http.get("selSchool");
      // console.log(res);
      if(res.status != 200){
        this.$message.error('获取数据失败');
      }else{
        this.schools = res.message;
        // console.log(this.schools);
      }
    },
    querySearch(queryString, cb) {
      var restaurants = this.schools;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    // value，value不能换成其他的
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      console.log(item);
    },
    // 添加文章按钮
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.Publish();
        } else {
          this.$message.error('error submit!!');
          return false;
        }
      });
    },
    // 添加文章
    async Publish(){
      this.dialogFormVisible = false;
      this.addUser.regtime = this.changeDate(new Date());
      this.addUser.birthday = this.changeDate(this.addUser.birthday);
      let index = this.getRandom(1,20);
      this.addUser.avatar = "/static/img/avatar/"+index+".jpg";
      let addUser = JSON.stringify(this.addUser);
      // console.log(this.addUser);
      const {data:res} = await this.$http.post("insertUser",{addUser});
      if(res.status != 200){
        this.$message.error('添加数据失败');
      }else{
        // console.log(res);
        this.$message({
          message: '发布成功',
          type: 'success'
        });
        this.getUserList();
      }
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 获取随机数
    getRandom(min, max){
      return Math.floor(Math.random() * (max - min + 1)) + min
    },
    // 转换时间格式
    changeDate(date){
      var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h=h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        minute = minute < 10 ? ('0' + minute) : minute;
        var second=date.getSeconds();
        second=second < 10 ? ('0' + second) : second;
        return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
    },

    // 每页条数
    handleSizeChange: function(newSize) {
      // console.log("newSize:"+newSize);
      this.queryUsers.pagesize = newSize;
      this.getUserList();
    },
    // 第几页
    handleCurrentChange: function(current) {
      // console.log("current:"+current);
      this.queryUsers.pagenum = current;
      this.getUserList();
    },
    // 修改按钮
    editOpen(item) {
      console.log(item);
      this.deitFormVisible=true;
      this.edituser = item;
      console.log(this.edituser);
    },
    // 点击修改
    async edit(edit){
      this.deitFormVisible = false;
      console.log("已修改");
      // edit.birthday = this.changeDate(edit.birthday);
      console.log(edit);
      edit = JSON.stringify(edit)
      const {data:res} = await this.$http.post("editUser",{edit});
      console.log(res);
      if(res.status != 200){
        this.$message.error("修改信息失败");
      }else{
        this.$message({
          message: '修改成功',
          type: 'success'
        });
        this.getUserList();
      }

    },
    // 删除部分
    handleClose(done){
      // this.$confirm('确定关闭？').then(_ => {
      //   done();
      // }).catch(_ => {})
    },
    async del(id) {
      this.dialogVisible = false;
      console.log("删除了");
      console.log(id);
      let variate = id;
      const {data:res} = await this.$http.post("delUser",{variate});
      // // console.log(result);
      if(res.status !==200){
        return this.$message.error("添加失败")
      }else{
        this.$message.success("删除成功")
        this.getUserList();
      }

    }
  }
}
</script>
<style scoped>
.el-select .el-input {
  width: 130px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
  /* width: 150px; */
}
.box-card {
  margin: 10px 0;
}
.el-button {
  margin: 0;
}
.el-table {
  margin: 10px 0;
}
</style>
